package me.linkcn.ydtxl.web.resource;

import me.linkcn.ydtxl.web.objects.Group;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: cmcc
 * Date: 11-8-17
 * Time: 下午4:47
 */
public class AccountResource extends BaseResource {
    String accountName;

    @Override
    protected void doInit() throws ResourceException {
        this.accountName = (String) getRequest().getAttributes().get("accountName");
    }

    @Get
    public Representation showAccount() throws IOException {
        this.accountName = (String) getRequest().getAttributes().get("accountName");
        ClientResource clientResource = new ClientResource(getServerUri() + "/" + this.accountName + "/group");
        Representation reply = clientResource.get();
        String json = reply.getText().trim();
        System.out.println(json);
        List<Group> groupList = new ArrayList<Group>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            JSONArray array = new JSONArray(json);
            for (int i = 0; i < array.length(); i++) {
                Group group = mapper.readValue(array.getString(i), Group.class);
                System.out.println(group);
                groupList.add(group);
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Map dataModel = new HashMap();
        dataModel.put("rootRef", getRequest().getRootRef());
        dataModel.put("serverUri", getServerUri());
        dataModel.put("accountName", this.accountName);
        dataModel.put("groupList", groupList);
        return getHTMLTemplateRepresentation("account.html", dataModel);
    }
}
